package org.witsoft.localmq.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName: SegmentList
 * @Description:
 * @Author: Colin
 * @Date: 2020/12/26 1:38 PM
 * @Version 1.0
 **/
public class SegmentList {

    private List<Segment> rawList = new ArrayList<>();

    public void addFirst(Segment item){
        rawList.add(0, item);
    }

    public Segment getFirst(){
        if(rawList.isEmpty()){
            return null;
        }
        return rawList.get(0);
    }

    public Segment findById(int id){
        for (Segment item : rawList) {
            if(item.getId() == id){
                return item;
            }
        }
        return null;
    }

    public Segment match(long num){
        for (Segment item : rawList) {
            if(num >= item.getStartOffset() && num <= item.getEndOffset()){
                return item;
            }
        }
        return null;
    }

    public List<Segment> filterEndOffsetLessThan(long offset){
        List<Segment> newList = new ArrayList<>();
        for (Segment item : rawList) {
            if(item.getEndOffset() < offset){
                newList.add(item);
            }
        }
        return newList;
    }

    public void remove(Segment item){
        rawList.remove(item);
    }

    public Collection<Segment> readOnly(){
        List<Segment> list = new ArrayList<>();
        for (Segment segment : rawList) {
            list.add(segment.clone());
        }
        return list;
    }
}
